//
//  OrderGoodsController.m
//  ios-supplier
//
//  Created by Benlai on 15/7/31.
//  Copyright (c) 2015年 feynmanyuan. All rights reserved.
//

#import "OrderGoodsController.h"
#import "GoodsMenuCell.h"

#import "JFBOrderGoodsMenuDS.h"
#import "JFBOrderGoodsProductDS.h"
#import "JFBLoadingAnimation.h"
#import "MemoryData.h"
#import "ShoppingCarController.h"

#define LIST_WIDTH_PERCENT  0.21
#define BOTTOM_HEIGHT 49
#define MERGIN 10
#define BAR_HEIGHT 64
#define MENU_TAG 100
#define MENU_CELL_HEIGHT 50
#define PRODUCT_CELL_HEIGHT 90

@interface OrderGoodsController () <ShoppingCarDelegate,UIGestureRecognizerDelegate>

@property (weak, nonatomic) IBOutlet UILabel *carGoodsNumberLabel;
@property (weak, nonatomic) IBOutlet UILabel *totalPriceLabel;
- (IBAction)goBuyGoods:(id)sender;
@property (nonatomic, strong) UITableView *menuView;
@property (nonatomic, strong) NSMutableArray *menuData;
@property (nonatomic, assign) NSInteger currentLabelIndex;
@property (nonatomic, assign) NSInteger cateTreeId;//类目ID
@property (nonatomic, assign) NSInteger cateTreeNodeId;//二级类目ID
@property (nonatomic, strong) UITableView *productTabelView;
@property (nonatomic, strong) NSMutableArray *productArray;

@end

@implementation OrderGoodsController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.currentLabelIndex = 0;
    self.menuData = [[NSMutableArray alloc] init];
    self.menuView = [[UITableView alloc] initWithFrame:CGRectMake(0, BAR_HEIGHT, self.view.frame.size.width * LIST_WIDTH_PERCENT, self.view.frame.size.height - BOTTOM_HEIGHT - BAR_HEIGHT) style:UITableViewStylePlain];
    self.menuView.tag = MENU_TAG;
    self.menuView.dataSource = self;
    self.menuView.delegate = self;
    self.menuView.showsVerticalScrollIndicator = NO;
    [self.menuView setSeparatorStyle: UITableViewCellSeparatorStyleNone];
    [self.view addSubview: self.menuView];
    
    self.productArray = [[NSMutableArray alloc]init];
    self.productTabelView = [[UITableView alloc]initWithFrame: CGRectMake(CGRectGetMaxX(self.menuView.frame) + MERGIN, BAR_HEIGHT, self.view.frame.size.width - MERGIN - self.menuView.frame.size.width, self.view.frame.size.height - BOTTOM_HEIGHT - BAR_HEIGHT) style: UITableViewStylePlain];
    self.productTabelView.dataSource = self;
    self.productTabelView.delegate = self;
    self.productTabelView.showsVerticalScrollIndicator = NO;
    [self.productTabelView setSeparatorStyle: UITableViewCellSeparatorStyleNone];
    [self.view addSubview: self.productTabelView];
    [self loadData];
    [self.productTabelView addLegendHeaderWithRefreshingTarget: self refreshingAction: @selector(refresh)];
    [self.navigationItem setLeftBarButtonItem: [self createBackView]];
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
}

-(void)viewWillAppear:(BOOL)animated
{
    [self shoppingCarGoodsChange];
}

-(void)refresh
{
    [self setProductData: self.currentLabelIndex isFirstLoad: NO];
}

-(void)loadData
{
    [self.menuData removeAllObjects];
    [JFBOrderGoodsMenuDS loadMenuList:^(NSArray *menuList, NSError *error) {
        [self.menuData addObjectsFromArray: menuList];
        [self.menuView reloadData];
        [self setProductData: 0 isFirstLoad: YES];
    } pager: nil];
}

-(void)historicalOrderBtnPressed
{
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView.tag == MENU_TAG) {
        return self.menuData.count;
    }
    else
    {
        return self.productArray.count;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.tag == MENU_TAG) {
        return MENU_CELL_HEIGHT;
    }
    return PRODUCT_CELL_HEIGHT;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.tag == MENU_TAG) {
        static NSString *identifier = @"listCell";
       GoodsMenuCell  *listCell = [tableView dequeueReusableCellWithIdentifier: identifier];
        if (listCell == nil) {
            listCell = [[GoodsMenuCell alloc] initWithStyle: UITableViewCellStyleDefault reuseIdentifier: identifier];
        }
        [listCell setSelectionStyle: UITableViewCellSelectionStyleNone];
        
        if (indexPath.row == self.currentLabelIndex) {
            [listCell setIsActive: YES];
        }
        else
        {
            [listCell setIsActive: NO];
        }
        JFBOrderGoodsMenuDS *menudata = self.menuData[indexPath.row];
        [listCell setName: menudata.name];
        return listCell;
    }
    else
    {
        static NSString *identifier = @"merchandiseCell";
        GoodsCell *cell = [tableView dequeueReusableCellWithIdentifier: identifier];
        if (cell == nil) {
            cell = [[GoodsCell alloc]initWithStyle: UITableViewCellStyleDefault reuseIdentifier: identifier cellWidth: tableView.frame.size.width];
        }
        [cell setSelectionStyle: UITableViewCellSelectionStyleNone];
        cell.productInfo = self.productArray[indexPath.row];
        cell.delegate = self;
        return cell;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.tag == MENU_TAG) {
        self.currentLabelIndex = indexPath.row;
        [self.menuView reloadData];
        [self setProductData: indexPath.row isFirstLoad: NO];
    }
}

-(void)setProductData: (NSInteger) row isFirstLoad: (BOOL)isFirst
{
    if (self.menuData.count <=0) {
        return;
    }
    JFBLoadingAnimation *animation;
    if (isFirst)
    {
        animation = [[JFBLoadingAnimation alloc] init: self.view];
    }
    JFBOrderGoodsMenuDS *menudata = self.menuData[row];
//    [JFBOrderGoodsProductDS loadProductList:^(NSArray *menuList, NSError *error) {
//        if (isFirst)
//        {
//            [animation stop];
//        }
//        [self.productTabelView.header endRefreshing];
//        [self.productArray removeAllObjects];
//        [self.productArray addObjectsFromArray: menuList];
//        [self.productTabelView reloadData];
//    } withLabelId: [UserInfo currentUser].merchantID.integerValue withCompanyId:4 withCateTreeId:menudata.cateTreeId withCateTreeNodeId:menudata.ID];
//    JFBOrderGoodsMenuDS *menudata = self.menuData[row];
    [JFBOrderGoodsProductDS loadProductList:^(NSArray *menuList, NSError *error) {
        if (isFirst)
        {
            [animation stop];
        }
        [self.productTabelView.header endRefreshing];
        [self.productArray removeAllObjects];
        [self.productArray addObjectsFromArray: menuList];
        [self.productTabelView reloadData];
    } withUT:[UserInfo currentUser].ut withLabelId:[[UserInfo currentUser].merchantID integerValue] withCompanyId:4 withCateTreeId:menudata.cateTreeId withCateTreeNodeId:menudata.ID withLimitClauseCount:1000 withLimitClauseStart:1];
}

-(void)cellGoodsChange
{
    NSInteger count = [[MemoryData sharedMemoryData] getCarGoodsNumber];
    self.carGoodsNumberLabel.text = [NSString stringWithFormat: @"%ld", count];
    double price = [[MemoryData sharedMemoryData] getTotalPrice];
    self.totalPriceLabel.text = [NSString stringWithFormat: @"￥%.2f", price];
}

-(void)shoppingCarGoodsChange
{
    [self.productTabelView reloadData];
    [self cellGoodsChange];
}

- (IBAction)goBuyGoods:(id)sender
{
    UIStoryboard *storyBoard = [UIStoryboard storyboardWithName: @"StoreManage" bundle: nil];
    ShoppingCarController *carC = (ShoppingCarController *)[storyBoard instantiateViewControllerWithIdentifier: @"shoppingCarController"];
    carC.delegate = self;
    [self.navigationController pushViewController: carC animated: YES];
}

- (UIBarButtonItem *)createBackView
{
    UIButton *leftButtonItem = [UIButton buttonWithType:UIButtonTypeCustom];
    leftButtonItem.frame = CGRectMake(0, 0, 11, 20);
    [leftButtonItem setBackgroundImage:[UIImage imageNamed:@"icon-Back"] forState:UIControlStateNormal];
    [leftButtonItem setImageEdgeInsets: UIEdgeInsetsMake((19 - 11) / 2, 0, (19 - 11) / 2, 0)];
    [leftButtonItem addTarget:self action:@selector(leftButtonItemClicked) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * item = [[UIBarButtonItem alloc] initWithCustomView:leftButtonItem];
    return item;
}

-(void)leftButtonItemClicked
{
    [self.navigationController popViewControllerAnimated:YES];
//    self.navigationController.navigationBar.hidden = YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
